// pages/yingyuan/detail.js
var timetool = require('../../utils/time.js');
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var pojo = ''
var reqfilmSign = '';
var cinemapojo = ''
var strAppCode = "2018SmallApp"
var imgpath = config.imgHost;
var filmcode = ''
var filmPojo = [];
var movielist = [];
var isSelected = 0;
var idx = 0;
var filePlanSgin = "";  //
var reqfilePlanSgin = ""; //获取电影日期签名
var reqplanSgin = "";  //获取电影排期签名
var startdate = "";
var enddate = "";
var showdate = [];
var plandate = []; //电影拍档
var curplandate = ''
var app = getApp();
var id = "";
var detail = "";
var code = "";
var finalMoney = "";
var Money = "";
var finalyuanMoney = "";
var CinemaCode = "";
var id = ""
var current = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indexnum: 0,
    chkid: 0,
    current: 0,
    chkmovieimg: '',//电影的图片
    dyid: 0,//电影id，
    dyname: '',//电影的名称
    pingfen: '评分:8.0分',
    shichang: '时长:120分钟',
    yyid: 0,//影院id
    yyname: '',//影院name
    address: '',//影院地址
    minprice: '30.0',//影院最低价
    movielist: [],//电影列表
    changcilist: [],//场次
    imgpath: imgpath,
    istoday: true,//默认今天
    isnextday: false,//明天
    islastday: false,//后天
    today: '',//今天的日期
    nextday: '',//明天的日期
    lastday: '',//后天的日期
    moreday: '',
    moreqday: '',
    morewday: '',
    moreeday: '',
    chkday: '',//选中的日期
    iswuchangci: false,//是否没有场次
    setWidth: '100%',
    isSelected: 0,
    isCurrent: 0,
    translateX: "50%"
  },
  /**购票**/
  gobuypiao: function (e) {
    console.log(12)
    var that = this;
    curplandate = e.currentTarget.dataset.pojo;//场次id
    var chkday = that.data.chkday;//选中的日期
    console.log(curplandate)
    console.log(detail)
    wx.navigateTo({
      url: '../huodongmovie/chooseseat?Cinemapojo=' + JSON.stringify(app.globalData.cinemapojo) + '&&plandate=' + JSON.stringify(curplandate) + '&&showdate=' + showdate[idx] + '&&detail=' + JSON.stringify(detail) + '&&EventId=' + id + '&&buyitem=' + isSelected + ''
    })
    //结束标识符
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    CinemaCode = app.globalData.cinemapojo.CinemaCode


    id = options.EventId;

    var that = this;
    if (app.globalData.hasLogin) { //TODO记得修改
      //TODO获取电影详情
      return req.ActivityFilmDetail(id).then(res => {

        if (res.data.success) {
          detail = res.data.data;
          for (var i = 0; i < detail.Films.length;i++){
            if (('' + detail.Films[i].UserScore).length > 1 && typeof (detail.Films[i].UserScore) != undefined) {

              detail.Films[i].UserScore = detail.Films[i].UserScore + ".0"


            } else {
              detail.Films[i].UserScore = "8.0"
            }
            if (detail.Films[i].PlayLongTime == null || typeof (detail.Films[i].PlayLongTime) == undefined){
              detail.Films[i].PlayLongTime ="120"
            }
          }
          console.log(detail)
          filmcode = detail.Films[0].FilmCode;
          detail.EventEnd = detail.EventEnd.split("T")[0];
          detail.EventStart = detail.EventStart.split("T")[0]

          Money = finalMoney = detail.PriceSale;
          finalyuanMoney = finalMoney + detail.EventDiscountValue;
        }
        that.setData({ detail, finalMoney, finalyuanMoney, phone: app.globalData.loginuserinfo.mobile, filmPojo })
        wx.setNavigationBarTitle({
          title: '选择排期',
        })
      }).then(() => {
        // filePlanSgin = "strAppCode=" + strAppCode + "CinemaCode=" + CinemaCode + "FilmCode=" + filmcode + "PlayStartDate=" + "PlayEndDate=";
        // return req.GetSignStr(filePlanSgin).then(res => {
        //   if (res.data.success)
        //     reqfilePlanSgin = res.data.data;

        // }).then(() => {

          return req.FilmDetail(filmcode, id).then(res => {

            startdate = res.data.data[0];
            showdate = [];
            for (let i = 0; i < startdate.FilmPlans.length; i++) {
              showdate.push(startdate.FilmPlans[i].PlayStartDate.substr(5, 10).replace("/", "-"))
            }
            console.log(showdate)
            plandate = startdate.FilmPlans[current].FilmPlanItems

            var heig = plandate.length * 120 + 'rpx'

            if (plandate.length <= 0) {
              that.setData({ iswuchangci: true, plandate: plandate, heig: '600rpx' })
            } else {
              for (var i = 0; i < plandate.length; i++) {
                var time = plandate[i].PlayStartTime.split(":")[0]
                if (time >= 4 && time < 18) {
                  //白天
                  plandate[i].sun = true;
                } else {
                  plandate[i].sun = false;
                }
              }

              that.setData({ plandate: plandate, iswuchangci: false, heig: heig, showdate: showdate })
            }
          })
        })
      
    } else {
      wx.login({
        success: function (res) {

          code = res.code;
          return req.MiniAppLogin(code).then(res => {
            if (res.data.notRegister) {//TODO记得修改
              wx.reLaunch({
                url: '../regiest/regiest?fromhuodongmovie=true&&EventId=' + id + ''
              })
            } else {

              var token = res.data.data
              //TODO请求用户信息
              app.globalData.hasLogin = true;
              app.globalData.token = token;
              return req.GetUserInfo(token).then(res => {
                if (res.data.success) {

                  app.globalData.loginuserinfo = res.data.data // res.data.data
                  that.setData({ detail, phone: app.globalData.loginuserinfo.mobile, hasLogin: true })

                  that.setData({ hasF: true })
                  wx.getUserInfo({
                    success: function (res) {
                      app.globalData.userinfo = res.userInfo

                      that.setData({ detail, phone: app.globalData.loginuserinfo.mobile })
                    }, fail: function () {
                      //拒绝授权
                    },
                  })

                } else {
                  wx.showModal({
                    title: '提示',
                    content: '登陆失败,请检查网络',
                  })
                }

              }).then(() => {
                return req.ActivityFilmDetail(id).then(res => {
                  if (res.data.success) {
                    detail = res.data.data;
                    for (var i = 0; i < detail.Films.length; i++) {
                      if (('' + detail.Films[i].UserScore).length > 1 && typeof (detail.Films[i].UserScore) != undefined) {

                        detail.Films[i].UserScore = detail.Films[i].UserScore + ".0"


                      } else {
                        detail.Films[i].UserScore = "8.0"
                      }
                      if (detail.Films[i].PlayLongTime == null || typeof (detail.Films[i].PlayLongTime) == undefined) {
                        detail.Films[i].PlayLongTime = "120"
                      }
                    }
                    console.log(detail)
                    // filmPojo = detail.Films;
                    // for (var i = 0; i < filmPojo.length;i++){
                    //   filmPojo[i].PlayStartDate = filmPojo[i].PlayStartDate.substring(6, filmPojo[i].PlayStartDate.length)
                    // }

                    filmcode = detail.Films[0].FilmCode;
                    detail.EventEnd = detail.EventEnd.split("T")[0];
                    detail.EventStart = detail.EventStart.split("T")[0]


                    Money = finalMoney = detail.PriceSale;
                    finalyuanMoney = finalMoney + detail.EventDiscountValue;
                  }
                  that.setData({ detail, finalMoney, finalyuanMoney, phone: app.globalData.loginuserinfo.mobile, filmPojo })
                  wx.setNavigationBarTitle({
                    title: '选择排期',
                  })
                }).then(() => {
                  // filePlanSgin = "strAppCode=" + strAppCode + "CinemaCode=" + CinemaCode + "FilmCode=" + filmcode + "PlayStartDate=" + "PlayEndDate=";
                  // return req.GetSignStr(filePlanSgin).then(res => {
                  //   if (res.data.success)
                  //     reqfilePlanSgin = res.data.data;

                  // }).then(() => {

                    return req.FilmDetail(filmcode, id).then(res => {

                      startdate = res.data.data[0];
                      showdate = [];
                      for (let i = 0; i < startdate.FilmPlans.length; i++) {
                        showdate.push(startdate.FilmPlans[i].PlayStartDate.substr(5, 10).replace("/", "-"))
                      }
                      console.log(showdate)
                      console.log(startdate)
                      plandate = startdate.FilmPlans[current].FilmPlanItems

                      var heig = plandate.length * 120 + 'rpx'

                      if (plandate.length <= 0) {
                        that.setData({ iswuchangci: true, plandate: plandate, heig: '600rpx' })
                      } else {
                        for (var i = 0; i < plandate.length; i++) {
                          var time = plandate[i].PlayStartTime.split(":")[0]
                          if (time >= 4 && time < 18) {
                            //白天
                            plandate[i].sun = true;
                          } else {
                            plandate[i].sun = false;
                          }
                        }

                        that.setData({ plandate: plandate, iswuchangci: false, heig: heig, showdate: showdate })
                      }

                    })
                  })
                })
              // })
            }
          })
        }, fail: function (res) {
          wx.showModal({
            title: '提示',
            content: '登陆失败',
          })
        }
      })
    }

  },
  selectedMove: function (e) {
    var Selected = e.currentTarget.id;
    this.setData({
      isSelected: isSelected
    })

  },
  /**
    * 滑动事件
    * **/
  scroll: function (e) {
    var that = this;

    var movielist = that.data.movielist;
    var indexnum = that.data.indexnum;
    //向右deltaX>0  向左侧deltaX<0 
    //scrollLeft判断滑动的宽度，获取选中的值
    //向左滑动
    if (e.detail.deltaX < 0) {
      var scrollnum = parseInt(e.detail.scrollLeft / 40);
      indexnum += scrollnum;

      if (indexnum < movielist.length) {
        that.setData({
          chkid: movielist[indexnum].id,
          indexnum: indexnum
        })
      } else {
        that.setData({
          chkid: movielist[movielist.length - 1].id,
          indexnum: movielist.length - 1
        })
      }
    }//向右滑动
    else if (e.detail.deltaX > 0) {
      var scrollnum = parseInt(e.detail.scrollLeft / 40);
      indexnum -= scrollnum;
      if (indexnum < 0) {
        that.setData({
          chkid: movielist[0].id,
          indexnum: 0
        })
      } else {
        that.setData({
          chkid: movielist[indexnum].id,
          indexnum: indexnum
        })
      }
    }
    that.getchkmovie();
  },
  //得到电影
  getchkmovie: function () {
    var that = this;
    var movielist = that.data.movielist;

    var txtarry = [];
    var dyname = "";//电影的名称
    var pingfen = "";//电影的评分
    var shichang = "";//电影的时长
    var chkmovieimg = "";//电影的海报
    //重置数据
    for (var j = 0; j < movielist.length; j++) {
      if (that.data.chkid == movielist[j].id) {
        txtarry[j] = {
          id: movielist[j].id,
          name: movielist[j].name,
          imgpath: movielist[j].imgpath,
          ischk: true,
          pingfen: movielist[j].pingfen,
          shichang: movielist[j].shichang
        }
        dyname = movielist[j].name;//电影的名称
        pingfen = movielist[j].pingfen;//电影的评分
        shichang = movielist[j].shichang;//电影的时长
        chkmovieimg = movielist[j].imgpath;//电影的时长
      } else {
        txtarry[j] = {
          id: movielist[j].id,
          name: movielist[j].name,
          imgpath: movielist[j].imgpath,
          ischk: false,
          pingfen: movielist[j].pingfen,
          shichang: movielist[j].shichang
        }
      }
    }

    that.setData({
      movielist: txtarry,
      dyid: that.data.chkid,//电影id，
      dyname: dyname,//电影的名称
      pingfen: pingfen,//电影的评分
      shichang: shichang,//电影的时长
      chkmovieimg: chkmovieimg,//电影的海报
    })


    //重置数据
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    isSelected = 0;
    idx = 0;
    var pmwidth = "";
    var pixelRatio = "";
    var that = this;

    wx.getSystemInfo({
      success: function (res) {
        pmwidth = res.screenWidth;
        pixelRatio = res.pixelRatio;
        console.log(pmwidth)
        console.log(pmwidth / 2 - (pmwidth / 5/2))
        console.log(pmwidth/5)
        that.setData({ pmwidth: (pmwidth / 2) - (pmwidth / 5/2) })
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },


  // 滑动切换tab 
  bindChange: function (e) {
    var that = this;
    that.setData({ currentTab: e.detail.current });
    this.setData({ current: e.detail.current })
    current = e.detail.current
    //TODO重新请求日子
    idx = e.detail.current



    plandate = startdate.FilmPlans[current].FilmPlanItems

    var heig = plandate.length * 120 + 'rpx'

    if (plandate.length <= 0) {
      that.setData({ iswuchangci: true, plandate: plandate, heig: '600rpx' })
    } else {
      for (var i = 0; i < plandate.length; i++) {
        var time = plandate[i].PlayStartTime.split(":")[0]
        if (time >= 4 && time < 18) {
          //白天
          plandate[i].sun = true;
        } else {
          plandate[i].sun = false;
        }
      }

      that.setData({ plandate: plandate, iswuchangci: false, heig: heig, showdate: showdate })
    }

    //   })
    // })
  },
  // 点击tab切换 
  swichNav: function (e) {
    this.setData({ current: e.currentTarget.dataset.current })
    //TODO 获取日期 发送请求


  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //得到场次的数据
  getchangcilist: function () {
    var that = this;
    //参数部分
    var dyid = that.data.dyid;
    var yyid = that.data.yyid;
    var riqi = that.data.chkday;
    //结束标识符
  },
  //结束标识符

  changeMovie: function (e) {
    var that = this;
    isSelected = e.detail.current
    this.setData({
      isSelected: e.detail.current,
      current: 0
    })
    filmcode = detail.Films[isSelected].FilmCode;

    // filePlanSgin = "strAppCode=" + strAppCode + "CinemaCode=" + CinemaCode + "FilmCode=" + filmcode + "PlayStartDate=" + "PlayEndDate=";
    // return req.GetSignStr(filePlanSgin).then(res => {
    //   if (res.data.success)
    //     reqfilePlanSgin = res.data.data;

    // }).then(() => {


      return req.FilmDetail(filmcode, id).then(res => {
        startdate = res.data.data[0];
        showdate = [];
        for (let i = 0; i < startdate.FilmPlans.length; i++) {
          showdate.push(startdate.FilmPlans[i].PlayStartDate.substr(5, 10).replace("/", "-"))
        }
        console.log(showdate)
        plandate = startdate.FilmPlans[current].FilmPlanItems

        var heig = plandate.length * 120 + 'rpx'

        if (plandate.length <= 0) {
          that.setData({ iswuchangci: true, plandate: plandate, heig: '600rpx' })
        } else {
          for (var i = 0; i < plandate.length; i++) {
            var time = plandate[i].PlayStartTime.split(":")[0]
            if (time >= 4 && time < 18) {
              //白天
              plandate[i].sun = true;
            } else {
              plandate[i].sun = false;
            }
          }

          that.setData({ plandate: plandate, iswuchangci: false, heig: heig, showdate: showdate })
        }
      })
    // })
  },

  selectedMove: function (e) {

    var isSelected = e.currentTarget.id
    this.setData({
      isSelected: isSelected
    })
  },
})